package com.lemon.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lemon.reggie.common.R;
import com.lemon.reggie.pojo.entity.Employee;
import com.lemon.reggie.pojo.entity.User;
import com.lemon.reggie.service.EmployeeService;
import com.lemon.reggie.service.UserService;
import com.lemon.reggie.utils.BaseContextUtil;
import com.lemon.reggie.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
//过滤器 -->拦截器 --> controller
//用FilterRegistrationBean注册过滤，可以控制过滤器的顺序
public class LoginFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Resource
    private EmployeeService employeeService;
    @Resource
    private UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //log.info("------当前请求的线程id为:{}", Thread.currentThread().getId());

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        //定义放行路径
        String[] urls = new String[]
                {
                    "/employee/login",
                    "/employee/logout",
                    "/backend/**",
                    "/front/**",
                    "/common/**",
                    "/user/sendMsg",
                    "/user/login",
                    "/doc.html",
                    "/webjars/**",
                    "/swagger-resources",
                    "/v2/api-docs"
                };
        /*  swagger文档需要放行的资源
        *   "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
        * */

        //符合放行路径
        if (this.checkUrl(urls, requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        //区分PC端和手机端登录过滤器校验，可以在前端的请求头中加一个标识，
        // 然后可以区分是PC端调用接口还是移动端调用接口

        //后台PC端登录
        //已登录，放行
        Long userId = (Long) request.getSession().getAttribute("userInfo");
        if (Objects.isNull(employeeService)) {
            employeeService = SpringUtils.getBean(EmployeeService.class);
        }

        Employee one = employeeService.getOne(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getId, userId).eq(Employee::getStatus, 1));

        if (Objects.nonNull(one)) {
            //set到当前线程的threadLocal中
            BaseContextUtil.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }


        //移动端已登录，放行
        Long userAppId = (Long) request.getSession().getAttribute("user");
        if (Objects.isNull(userService)) {
            userService = SpringUtils.getBean(UserService.class);
        }

        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, userAppId).eq(User::getStatus, 1));
        if (Objects.nonNull(user)) {
            BaseContextUtil.setCurrentId(userAppId);
            filterChain.doFilter(request, response);
            return;
        }

        //未登录，响应给服务器
        response.getWriter().println(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean checkUrl(String[] urls,String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
